package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.MessagesApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class MessagesApiImpl implements MessagesApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 往数据库中好友表中插入两条数据
     * @param userId
     * @param loginUserId
     */
    @Override
    public void addContacts(Long userId, Long loginUserId) {
        long nowTime = System.currentTimeMillis();

        addFriend(userId,loginUserId,nowTime);
        addFriend(loginUserId,userId,nowTime);

    }

    private void addFriend(Long loginUserId, Long userId, long nowTime) {

        // 判断是否已经添加过了
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(loginUserId).and("friendId").is(userId));
        boolean exists = mongoTemplate.exists(query, Friend.class);

        if (!exists){
            // 如果不存在，则插入数据
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(loginUserId);
            friend.setCreated(nowTime);
            mongoTemplate.insert(friend);
        }

    }
}
